/* go.c */
#include "common.h"

int main(int argc, char *argv[])
{
    if (!(argc == 4 || (argc == 2 && atoi(argv[1]) == HOST_CMD_EXIT)))
    {
        fprintf(stderr, "Usage:\n"
                        "  Normal command: %s <CMD_ID> <value1> <value2>\n"
                        "  Exit command:   %s 500\n",
                argv[1], argv[1]);
        return EXIT_FAILURE;
    }

    // 访问共享内存
    int shmid = shmget(SHM_KEY, 0, 0666);
    if (shmid == -1)
    {
        perror("shmget");
        return EXIT_FAILURE;
    }

    shm_buf_data_t *shm_data = (shm_buf_data_t *)shmat(shmid, NULL, 0);
    if (shm_data == (void *)-1)
    {
        perror("shmat");
        return EXIT_FAILURE;
    }

    // 准备命令数据
    shm_data->cmd_id = atoi(argv[1]);
    if (shm_data->cmd_id != HOST_CMD_EXIT)
    {
        shm_data->param = atoi(argv[2]);
        shm_data->value = atoi(argv[3]);
    }

    // 通知信号量
    int semid = semget(SEM_KEY, 0, 0666);
    if (semid == -1)
    {
        perror("semget");
        return EXIT_FAILURE;
    }

    struct sembuf sops = {.sem_num = 0, .sem_op = 1, .sem_flg = 0};
    if (semop(semid, &sops, 1) == -1)
    {
        perror("semop");
        return EXIT_FAILURE;
    }

    DEBUG("Command sent - ID: %d", shm_data->cmd_id);
    shmdt(shm_data);
    return EXIT_SUCCESS;
}
